package com.chenwang.measure.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;

import com.chenwang.measure.R;
import com.chenwang.measure.base.BaseActivity;
import com.chenwang.measure.model.Constant;
import com.chenwang.measure.model.bean.LocationBean;
import com.chenwang.measure.model.bean.LonLatBean;
import com.chenwang.measure.model.bean.PointBean;
import com.chenwang.measure.model.bean.Task;
import com.chenwang.measure.ui.dialog.MeasureLoadingDialog;
import com.chenwang.measure.ui.view.TitleLayout;
import com.chenwang.measure.utils.DistanceUtils;
import com.chenwang.measure.utils.FileUtils;
import com.chenwang.measure.utils.MyCrashHandler;
import com.chenwang.measure.utils.MyLogger;
import com.chenwang.measure.utils.MyToast;
import com.chenwang.measure.utils.RxTime;
import com.chenwang.measure.utils.SharePreferenceUtils;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;



//任务测量详情
public class MeasureDetailActivity extends BaseActivity {
    private static final String Tag ="measureDetail";
    @BindView(R.id.title)
    TitleLayout mTitleLayout;
    @BindView(R.id.tv_start)
    TextView mTvStart;
    @BindView(R.id.tv_measure_start)
    TextView mTvMeasureStart;
    @BindView(R.id.tv_end)
    TextView mTvEnd;
    @BindView(R.id.tv_measure_end)
    TextView mTvMeasureEnd;
    @BindView(R.id.iv_location)
    ImageView mIvLocation;
    @BindView(R.id.tv_measure)
    TextView mTvMeasureDistance;  //距离
    @BindView(R.id.tv_lat)
    TextView mTvLat;
    @BindView(R.id.tv_lon)
    TextView mTvLon;
    @BindView(R.id.tv_height)
    TextView mTvHeight;
    @BindView(R.id.tv_satellite_total)
    TextView mTvSatelliteTotal;
    @BindView(R.id.tv_satellite)
    TextView mTvSatellite;
    @BindView(R.id.spin_kit)
    ProgressBar mProgressBar;
    @BindView(R.id.tv_show_status)
    TextView mTvShowStatus;
    @BindView(R.id.et_result)
    EditText mEtResult;//输入测量结果
    @BindView(R.id.btn_result)//手动输入结果按钮
    Button mBtnResult;
    @BindView(R.id.iv_stop)
    ImageView mIvStop;  //曲线 停止 继续
    @BindView(R.id.tv_stop)
    TextView mTvStop;    //曲线  停止 继续文本
    @BindView(R.id.tv_teleseme)
    TextView mTvCount;//显示当前要测量的信号机
    @BindView(R.id.tv_location_status)
    TextView mTvLocationStatus;//定位状态 0未解算 16单点定位 17差分定位 50固定解
    @BindView(R.id.rb_statr)
    RadioButton mRbStatr; //开始点
    @BindView(R.id.rb_end)
    RadioButton mRbEnd;  //结束点
    @BindView(R.id.rb_1)
    RadioButton mRb1;  //直线
    @BindView(R.id.rb_2)
    RadioButton mRb2; //折线
    @BindView(R.id.rb_3)
    RadioButton mRb3;  //曲线
    private int mLine = 1;//1默直 2曲 3折
    private Double mLatStart;//起始点纬度
    private Double mLonStart;//起始点经度
    private Double mLatEnd;//结束点纬度
    private Double mLonEnd;//结束点经度
    private int mNumber;//定位次数
    private double mDistance = 0.0;//测量结果距离
    private RxTime mRxTime2;//曲线 定时器
    private LonLatBean mLonLatBean =new LonLatBean(); // 保存折线上一次的点
    private RxTime mRxTime;//经纬度 卫星等 状态 定时器
    private MeasureLoadingDialog mDialog = null;//定位对话框
    private int mCount;//折线计数
    private boolean isStop;//曲线 停止 继续 状态
    private List<LonLatBean> mLonLatBeans = new ArrayList<>();//
    private List<PointBean> mPointList  = new ArrayList<>();
    private int mStartEndFlag;//0 默认开始点  1结束点
    private String mMultipoint =""; //连续点
    private Task.Segment mSegmentBean; //当前测量段数据
    private int mMeasured; //点 位是否测量过  0 未   1 开始  2结束  3点都测量过 4完成
    @BindView(R.id.tv_status)
    TextView mTvStatus;
    private Task.Segment mAgainMeasure;
    private int mIsFixed;
    private double mHorizontal;  //水平精度
    private String crashSegment = "crash_segment";//保存数据到sp中


    @Override
    public int setLayoutId() {
        return R.layout.activity_measure_detail;
    }
    //直 折 曲线 的点击事件
    public void onLineType(View view) {
        switch (view.getId()) {
            case R.id.rb_1:
                if (mLine != 1)
                    showLine1();
                break;
            case R.id.rb_2://折线
                if (mLine != 3)
                    showLine2();
                break;
            case R.id.rb_3://曲线
                if (mLine != 2)
                    showLine3();
                break;
        }


    }
    //直线
    private void showLine1() {
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setTitle("直线");
        normalDialog.setMessage("是否切换直线");
        normalDialog.setCancelable(false);
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mLine = 1;
                        MyToast.show("直线");
                        initMeasureLine1();
                        mTvCount.setVisibility(View.INVISIBLE);
                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (mLine){
                            case 1:
                                break;
                            case 2:
                                mRb3.setChecked(true);
                                break;
                            case 3:
                                mRb2.setChecked(true);
                                break;
                        }
                        dialog.dismiss();
                    }
                });
        normalDialog.show();

    }
    //折线
    private void showLine2() {
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setTitle("折线");
        normalDialog.setMessage("是否切换折线");
        normalDialog.setCancelable(false);
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mLine = 3;
                        //判断上次是否为曲线
                        if (line2Count == 1) {
                            mCount = 1;
                            MyToast.show("由曲线变更为折线测量");
                            //隐藏曲线测量时的显示view
                            mProgressBar.setVisibility(View.INVISIBLE);
                            mTvShowStatus.setVisibility(View.INVISIBLE);
                            mTvStop.setVisibility(View.INVISIBLE);
                            mIvStop.setVisibility(View.INVISIBLE);
                            if (mRxTime2 != null) { //关闭曲线定时器
                                mRxTime2.cancel();
                            }
                        } else {
                            mDistance = 0.0;
                            MyToast.show("折线");
                        }
                        initMeasureLine3();
                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (mLine){
                            case 1:
                                mRb1.setChecked(true);
                                break;
                            case 2:
                                mRb3.setChecked(true);
                                break;
                            case 3:
                                mRb2.setChecked(true);
                                break;
                        }
                        dialog.dismiss();
                    }
                });
        normalDialog.show();

    }

    //曲线
    private void showLine3() {
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setTitle("曲线");
        normalDialog.setMessage("是否切换曲线");
        normalDialog.setCancelable(false);
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mLine = 2;
                        //line3Count为1 表示由折线变更为曲线测量
                        if (line3Count == 1) {
                            MyToast.show("由折线变更为曲线测量");
                        } else {
                            mDistance = 0.0;
                            MyToast.show("曲线");
                        }
                        initMeasureLine2();
                        mTvCount.setVisibility(View.INVISIBLE);
                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (mLine){
                            case 1:
                                mRb1.setChecked(true);
                                break;
                            case 2:
                                mRb3.setChecked(true);
                                break;
                            case 3:
                                mRb2.setChecked(true);
                                break;
                        }
                        dialog.dismiss();
                    }
                });
        normalDialog.show();

    }


    @Override
    protected void onResume() {
        super.onResume();
        initMeasure();//获取取点次数   固定解    水平精度

    }

    //初始化测量信息
    private void initSegment(){
        if (getIntent().getParcelableExtra("data") != null) {
            //获取要测量的信号机数据信息
            mSegmentBean = getIntent().getParcelableExtra("data");//获取测量点数据
           /* List<Integer> start = getIntent().getIntegerArrayListExtra("start");//
            List<Integer> end = getIntent().getIntegerArrayListExtra("end");//
            if (end != null)
                mSegmentBean.getEnd().setGroupId(end);
            if (start != null)
                mSegmentBean.getStatr().setGroupId(start);*/
            mAgainMeasure = mSegmentBean;
            //设置信号机名字
            mRbStatr.setText(mSegmentBean.getStatr().getStationName() + mSegmentBean.getStatr().getSemaphoreName());//结束信号机
            mRbEnd.setText(mSegmentBean.getEnd().getStationName() + mSegmentBean.getEnd().getSemaphoreName());//开始信号机
            mMeasured = mSegmentBean.getState(); //获取点的状态
            mSegmentBean.setLineType(mLine); //将默认测量直线添加
            initMeasureLine1();//直线  初始化有没有测量过的点位
        }
    }

    @Override
    public void initData() {
        super.initData();
        ButterKnife.bind(this);
        initLocation();//信息定位
        mRbStatr.setClickable(false);
        mRbEnd.setClickable(true);
        mTitleLayout.setClickListenertLeft(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialogBack();//返回提示
            }
        });
        String json = SharePreferenceUtils.getString(this, crashSegment,"" );
        if (TextUtils.isEmpty(json)) {
            initSegment();
        } else {
            showRecoverDialog(json);
        }


    }


    //恢复
    private void recover(String json){
        try {
            MyLogger.i(json);
            Gson gson = new Gson();
            mSegmentBean = gson.fromJson(json, Task.Segment.class);
            mAgainMeasure = mSegmentBean;
            mRbStatr.setText(mSegmentBean.getStatr().getStationName() + mSegmentBean.getStatr().getSemaphoreName());//结束信号机
            mRbEnd.setText(mSegmentBean.getEnd().getStationName() + mSegmentBean.getEnd().getSemaphoreName());//开始信号机
            mMultipoint = mSegmentBean.getStatr().getMultipoint();
            mCount = mSegmentBean.getCount();
            mLatEnd = mSegmentBean.getLatEnd();
            mLonEnd = mSegmentBean.getLonEnd();
            mLatStart = mSegmentBean.getLatStart();
            mLonStart = mSegmentBean.getLonStart();
            if (mSegmentBean.getLonLat() != null) {
                mLonLatBean = mSegmentBean.getLonLat();
            }
            mDistance = mSegmentBean.getDistance();
            line1Count = mSegmentBean.getLine1Count();
            line2Count = mSegmentBean.getLine2Count();
            line3Count = mSegmentBean.getLine3Count();
            mLine = mSegmentBean.getLineType();
            mStartEndFlag = mSegmentBean.getStartEndFlag();
            mMeasured = mSegmentBean.getState();
            switch (mLine) {
                case 1:
                    mRb1.setChecked(true);//直线
                    if (mLatStart != null && mLonStart != null)
                        mRbStatr.setTextColor(ContextCompat.getColor(MeasureDetailActivity.this, R.color.colorBlue));
                    if (mLatEnd != null && mLonEnd != null)
                        mRbEnd.setTextColor(ContextCompat.getColor(MeasureDetailActivity.this, R.color.colorBlue));
                    break;
                case 2:
                    mRb3.setChecked(true);//曲线
                    line2Measure();
                    break;
                case 3:
                    if (mCount >= 1) {
                        mTvCount.setText("下次点：p" + mCount);
                        mTvCount.setVisibility(View.VISIBLE);

                    }
                    mRb2.setChecked(true);//折线
                    break;

            }
            switch (mStartEndFlag) {
                case 0:
                    mRbStatr.setChecked(true);
                    break;
                case 1:
                    mRbEnd.setChecked(true);
                    break;
            }

            mTvMeasureDistance.setText("测量结果：" + mDistance);
           // SharePreferenceUtils.putString(this, crashSegment, "");
        }catch (Exception e){
            MyCrashHandler.newInstance().saveCrashInfoToFile(e);

        }

    }

    //重新测量
    private void againMeasure(){
        mSegmentBean = mAgainMeasure;
        mSegmentBean.setLineType(mLine);
        mRbEnd.setTextColor(ContextCompat.getColor(this,R.color.black_333333));
        mRbStatr.setTextColor(ContextCompat.getColor(this,R.color.black_333333));
        mRbStatr.setClickable(false);
        mRbEnd.setClickable(true);
        mRbStatr.setChecked(true);
        mDistance = 0.0;
        mTvMeasureDistance.setText("测量结果：" + mDistance);
        mTvCount.setVisibility(View.INVISIBLE);
        mStartEndFlag =0;
        line1Count=0;

        switch (mLine){
            case 2:
                line2Count =0;
                mMultipoint="";
                mPointList.clear();
                mIvStop.setImageResource(R.mipmap.ic_stop);
                mTvStop.setText("停止");
                mProgressBar.setVisibility(View.INVISIBLE);//隐藏
                mTvShowStatus.setVisibility(View.INVISIBLE);
                mTvStop.setVisibility(View.INVISIBLE);
                mIvStop.setVisibility(View.INVISIBLE);
                isStop = true;
                if (mRxTime2 != null) {
                    mRxTime2.cancel();
                }
                initMeasureLine2();
                break;
            case 3:
                mCount =0;
                line3Count =0;
                mMultipoint="";

                initMeasureLine3();
                break;

        }
        MyToast.show("数据清除成功");
    }




    //初始化测量 判断是否有测量过的点 直线
    private void initMeasureLine1(){
        switch (mMeasured){
            case 0:
                mRbStatr.setClickable(false);//不可点击
                mRbEnd.setClickable(true);//可点击
                break;
            case 1://开始点已测量过
                 mRbStatr.setClickable(false);
                 mRbEnd.setClickable(true);
                 line1Count =1;//表示直线测过一个点
                 mLatStart = DistanceUtils.getLat(mSegmentBean.getStatr().getLonAndlat());//纬度
                 mLonStart = DistanceUtils.getLon(mSegmentBean.getStatr().getLonAndlat());//经度
                 mRbStatr.setTextColor(ContextCompat.getColor(this,R.color.colorBlue));//将测过的点颜色为蓝色
                break;
            case 2://结束点已测量过
                mRbStatr.setClickable(false);
                mRbEnd.setClickable(true);
                line1Count =1; //表示直线测过一个点
                //mStartEndFlag =0; //信号机结束点
                mLatEnd = DistanceUtils.getLat(mSegmentBean.getEnd().getLonAndlat());//纬度
                mLonEnd = DistanceUtils.getLon(mSegmentBean.getEnd().getLonAndlat());//经度
               // savePoint(mLonEnd,mLatEnd );
                mRbEnd.setTextColor(ContextCompat.getColor(this,R.color.colorBlue));//将测过的点颜色为蓝色
                break;
            case 3://算出来 两点都测量过 表示重测
                mRbStatr.setClickable(false);
                mRbEnd.setClickable(true);
                mRbEnd.setTextColor(ContextCompat.getColor(this,R.color.colorBlue));
                mRbStatr.setTextColor(ContextCompat.getColor(this,R.color.colorBlue));
                mTvMeasureDistance.setText("测量结果："+ mSegmentBean.getStatr().getSemaphoreSpace());
                break;
            case 4://已测量完成的  表示重测
                mRbStatr.setClickable(false);
                mRbEnd.setClickable(true);
                mRbEnd.setTextColor(ContextCompat.getColor(this,R.color.colorBlue));
                mRbStatr.setTextColor(ContextCompat.getColor(this,R.color.colorBlue));
                mTvMeasureDistance.setText("测量结果："+ mSegmentBean.getStatr().getSemaphoreSpace());
                break;
        }

    }

    //初始化测量 判断是否有测量过的点 曲线
    private void initMeasureLine2(){
        if ((mMeasured ==1)||(mMeasured ==2)){
            if (line1Count ==1){
            line1Count =0;
            }
        }
        switch (mMeasured){
            case 0:
                mRbStatr.setClickable(false);
                mRbEnd.setClickable(true);
                break;
            case 1:
                mRbStatr.setClickable(false);
                mRbEnd.setClickable(true);
                mLatStart = DistanceUtils.getLat(mSegmentBean.getStatr().getLonAndlat());//纬度
                mLonStart = DistanceUtils.getLon(mSegmentBean.getStatr().getLonAndlat());//经度
                mRbStatr.setTextColor(ContextCompat.getColor(this,R.color.colorBlue));
              //  savePoint(mLonStart,mLatStart );
                break;
            case 2:
                mRbStatr.setClickable(true);
                mRbEnd.setClickable(false);
                mRbEnd.setChecked(true);
                mStartEndFlag =1;
                mLatEnd = DistanceUtils.getLat(mSegmentBean.getEnd().getLonAndlat());//纬度
                mLonEnd = DistanceUtils.getLon(mSegmentBean.getEnd().getLonAndlat());//经度
                mRbEnd.setTextColor(ContextCompat.getColor(this,R.color.colorBlue));
                break;
            case 3://两点已测量
                mRbStatr.setClickable(false);
                mRbEnd.setClickable(true);
                mRbEnd.setTextColor(ContextCompat.getColor(this,R.color.colorBlue));
                mRbStatr.setTextColor(ContextCompat.getColor(this,R.color.colorBlue));
                break;
            case 4:
                mRbStatr.setClickable(false);
                mRbEnd.setClickable(true);
                mRbEnd.setTextColor(ContextCompat.getColor(this,R.color.colorBlue));
                mRbStatr.setTextColor(ContextCompat.getColor(this,R.color.colorBlue));
                break;
        }

    }

    //初始化测量 判断是否有测量过的点 折线
    private void initMeasureLine3(){
        if ((mMeasured ==1)||(mMeasured ==2)){
            if (line1Count ==1){
                line1Count =0;
            }
        }
        switch (mMeasured){
            case 0:
                mRbStatr.setClickable(false);
                mRbEnd.setClickable(true);
                break;
            case 1:
                mRbStatr.setClickable(false);
                mRbEnd.setClickable(true);
                mLonLatBean.setLon(DistanceUtils.getLon(mSegmentBean.getStatr().getLonAndlat()));
                mLonLatBean.setLat(DistanceUtils.getLat(mSegmentBean.getStatr().getLonAndlat()));
                mRbStatr.setTextColor(ContextCompat.getColor(this,R.color.colorBlue));
                mLonStart = mLonLatBean.getLon();
                mLatStart = mLonLatBean.getLat();
                line3Count =1;
                mCount++;
                mTvCount.setText("下次点：p1");
                mTvCount.setVisibility(View.VISIBLE);
                break;
            case 2:
                mRbStatr.setClickable(true);
                mRbEnd.setClickable(false);
                mRbEnd.setChecked(true);
                mStartEndFlag =1;
                mLonLatBean.setLon(DistanceUtils.getLon(mSegmentBean.getEnd().getLonAndlat()));
                mLonLatBean.setLat(DistanceUtils.getLat(mSegmentBean.getEnd().getLonAndlat()));
                mRbEnd.setTextColor(ContextCompat.getColor(this,R.color.colorBlue));
                mLonEnd = mLonLatBean.getLon();
                mLatEnd = mLonLatBean.getLat();
                line3Count =1;
                mCount++;
                mTvCount.setText("下次点：p1");
                mTvCount.setVisibility(View.VISIBLE);
                break;
            case 3:
                mRbStatr.setClickable(false);
                mRbEnd.setClickable(true);
                mRbEnd.setTextColor(ContextCompat.getColor(this,R.color.colorBlue));
                mRbStatr.setTextColor(ContextCompat.getColor(this,R.color.colorBlue));
                break;
            case 4:
                mRbStatr.setClickable(false);
                mRbEnd.setClickable(true);
                mRbEnd.setTextColor(ContextCompat.getColor(this,R.color.colorBlue));
                mRbStatr.setTextColor(ContextCompat.getColor(this,R.color.colorBlue));
                break;
        }

    }



    //初始化定位次数
    private void initMeasure() {
            mNumber = SharePreferenceUtils.getInt(this, Constant.LOCATION_NUMBER, 10)- 1;
           mIsFixed = SharePreferenceUtils.getInt(this,"fixed" , 0);
           mHorizontal = Double.valueOf(SharePreferenceUtils.getString(this,Constant.HORIZONTAL , "0.5"));
    }



    @OnClick({R.id.tv_photo,R.id.iv_location, R.id.btn_save, R.id.btn_result, R.id.iv_stop,R.id.tv_setting,R.id.tv_measure_state})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_measure_state:
                if (mLine != 1){
                    showAgainDialog();
                }else {
                    MyToast.show("折线或曲线才能重测");
                }

                break;
            case R.id.tv_setting:
                startActivity(new Intent(this, MeasureSettingActivity.class));
                break;
            case R.id.tv_photo://打开相册
                 openPhoto();
                 break;
            case R.id.iv_stop://曲线暂停继续
                if (isStop) {
                    mIvStop.setImageResource(R.mipmap.ic_start);
                    mProgressBar.setVisibility(View.INVISIBLE);
                    mTvShowStatus.setVisibility(View.INVISIBLE);
                    mTvStop.setText("继续");
                    isStop = false;
                } else {
                    mProgressBar.setVisibility(View.VISIBLE);//显示定位效果图
                    mTvShowStatus.setVisibility(View.VISIBLE);//显示定位中文本
                    mIvStop.setImageResource(R.mipmap.ic_stop);
                    mTvStop.setText("停止");
                    isStop = true;
                }
                saveData();

                break;
            case R.id.btn_result:
                setResult();
                break;
            case R.id.btn_save:
                if (isResult){
                    showSaveDialog();
                }else {
                    if (TextUtils.isEmpty(mSegmentBean.getStatr().getSemaphoreSpace())) {
                        MyToast.show("距离不能为空");
                    } else if (TextUtils.isEmpty(mSegmentBean.getStatr().getLonAndlat())) {
                        MyToast.show("请开始测量起始点");
                    } else if (TextUtils.isEmpty(mSegmentBean.getEnd().getLonAndlat())) {
                        MyToast.show("请开始测量结束点");
                    } else {
                        showSaveDialog();
                    }
                }

                break;
            case R.id.iv_location: //定位
                if (mIsFixed ==1){
                    int pos = LocationBean.getInstance().getPos();//获取定位状态
                    if (pos==50){
                        location();
                    }else {
                        startMediaPlayer();
                        MyToast.show("固定解已锁定");
                    }
                }else {
                    location();
                }
                saveData();

                break;

        }

    }



    //求平均
    private LonLatBean average() {
        int total = mLonLatBeans.size();
        double lat = 0, lon = 0;
        for ( LonLatBean offsetBean: mLonLatBeans){
            MyLogger.i("经纬度"+offsetBean.getLon()+"---"+offsetBean.getLat());
            lat += offsetBean.getLat() * Math.PI / 180;
            lon += offsetBean.getLon() * Math.PI / 180;
        }
        lat /= total;
        lon /= total;
        LonLatBean offsetBean = new LonLatBean();
        offsetBean.setLat(lat * 180 / Math.PI);
        offsetBean.setLon(lon * 180 / Math.PI);
        MyLogger.i("经纬度"+offsetBean.getLon()+"---"+offsetBean.getLat());
        return offsetBean;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mRxTime != null) {
            mRxTime.cancel();
        }
    }
    int i = 0;
    //更新经纬度等信息
    private void initLocation() {
        mRxTime = new RxTime();
        mRxTime.interval(1000, new RxTime.RxAction() {
            @Override
            public void action(long number) {
                if (LocationBean.getInstance().isState()){
                    mTvStatus.setText("设备已连接");
                }else {
                    mTvStatus.setText("设备未连接");

                }
                if (!TextUtils.isEmpty(LocationBean.getInstance().getLat() + "")) {
                    mTvLat.setText("纬度：" + LocationBean.getInstance().getLat());
                    mTvLon.setText("经度：" + LocationBean.getInstance().getLon());
                    mTvHeight.setText("高度：" + LocationBean.getInstance().getHight());
                    setLocationStatus(LocationBean.getInstance().getPos());
                    mTvSatelliteTotal.setText(mLonLatBeans.size()+"卫星总数：" + LocationBean.getInstance().getSatelliteTotal());
                    mTvSatellite.setText("水平:" + DistanceUtils.decimalFour(LocationBean.getInstance().getHorizontal())+" 高:"+DistanceUtils.decimalFour(LocationBean.getInstance().getVertrcal()));

                }

            }
        });

    }

    //设置定位状态
    private void setLocationStatus(int status) {
        switch (status) {
            case 0:
                mTvLocationStatus.setText("未解算: 0");
                break;
            case 16:
                mTvLocationStatus.setText("单点定位: 16");
                break;
            case 17:
                mTvLocationStatus.setText("差分定位: 17");
                break;
            case 50:
                mTvLocationStatus.setText("固定解: 50");
                break;
            case 18:
                mTvLocationStatus.setText("SBAS: 18");
                break;
            case 34:
                mTvLocationStatus.setText("浮点解: 34");
                break;
        }

    }

    //显示定位对话框
    private void showDialog() {
        mDialog = new MeasureLoadingDialog();
        mDialog.show(getSupportFragmentManager(), "");
    }

    //关闭对话框
    private void dismissDialog() {
        if (mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }
    }

    private boolean isResult ; //是否是手动确定结果 5

    //手动确定测量结果
    private void setResult() {
        String result = mEtResult.getText().toString().trim();
        if (TextUtils.isEmpty(result)) {
            MyToast.show("不能为空");
        } else {
            isResult =true;
            mDistance = Double.valueOf(result);
            mTvMeasureDistance.setText("测量结果：" + result + "m");
            mSegmentBean.setDistance(mDistance);
        }
    }
    //播放精度不足声音
    private void startMediaPlayer() {
        MediaPlayer.create(this,R.raw.low_precision).start();
     }

     //曲线拟合
     private double fitting(){
        if (mPointList.size()>2) {
            double d = 0.0;
            int n = 2;
            mPointList = DistanceUtils.CurveFitter(mPointList, n);
            for (int i = 0; i < mPointList.size() - 1; i++) {
                d += DistanceUtils.decimalTwo(DistanceUtils.getDistance(mPointList.get(i).getLon()
                        , mPointList.get(i).getLat(), mPointList.get(i + 1).getLon(), mPointList.get(i + 1).getLat()));
            }
        return d;
        }
        return 0;

     }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    final List<LocalMedia> list = PictureSelector.obtainMultipleResult(data);
                    int i = list.get(0).getCompressPath().lastIndexOf("/");
                    int p = list.get(0).getCompressPath().lastIndexOf(".");


                            if (mStartEndFlag ==0){

                                mSegmentBean.getStatr().setImageUrl(list.get(0).getCompressPath());
                            }else {
                                mSegmentBean.getEnd().setImageUrl(list.get(0).getCompressPath());

                            }
                            MyToast.show("添加成功");


                    break;
            }
        }
    }

    //打开相册
    public void openPhoto() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .minSelectNum(1)
                .selectionMode(PictureConfig.SINGLE)
                .previewImage(true)
                .isCamera(true)
                .compress(true)
                .enableCrop(false)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    //开始点
    private void showStart(){

        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setTitle("开始点");
        normalDialog.setMessage("是否切换开始点");
        normalDialog.setCancelable(false);

        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mStartEndFlag = 0;//0 开始信号机  1结束点信号机  标识
                        MyToast.show("开始点");
                        if (mLine !=2) {
                            if (line3Count == 1) {
                                line3Count = 2;
                            }
                        }
                        lineFinish();
                        mRbStatr.setClickable(false);
                        mRbEnd.setClickable(true);
                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mRbEnd.setChecked(true);
                        mRbStatr.setClickable(true);
                        mRbEnd.setClickable(false);
                        dialog.dismiss();
                    }
                });
        normalDialog.show();

    }

    //结束点
    private void showEnd(){

        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setTitle("结束点");
        normalDialog.setMessage("是否切换结束点");
        normalDialog.setCancelable(false);
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mStartEndFlag = 1; //0 开始信号机  1结束点信号机  标识
                        MyToast.show("结束点");
                        if (mLine !=2) {
                            if (line3Count == 1) {
                                line3Count = 2;
                            }
                        }
                        lineFinish();
                        mRbStatr.setClickable(true);
                        mRbEnd.setClickable(false);

                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        mRbStatr.setChecked(true);
                        mRbStatr.setClickable(false);
                        mRbEnd.setClickable(true);
                        dialog.dismiss();
                    }
                });
        normalDialog.show();

    }


    //信号机开始结束监听事件
    public void onStatrEnd(View view) {
        switch (view.getId()){
            case R.id.rb_statr://开始点
                showStart();
                break;
            case R.id.rb_end://结束点
                showEnd();
                break;
        }
    }

    private int line1Count ;//直线
    private int line2Count ;//曲线
    private int line3Count ;//折线
    //获取有效的当前经纬度
    private LonLatBean getValidLatLon(){
        LonLatBean offsetBean= new LonLatBean();
        offsetBean.setLat(LocationBean.getInstance().getLat());
        offsetBean.setLon(LocationBean.getInstance().getLon());
        offsetBean.setHorizontal(LocationBean.getInstance().getHorizontal());
        int pos = LocationBean.getInstance().getPos();//获取定位状态
        //定位状态必须是 17 50 34 并且精度小于等于 设置的精度
        if ((pos == 17) || (pos == 50) || (pos == 34) && (offsetBean.getHorizontal() <= mHorizontal)) {
            if (mLonLatBeans != null && mLonLatBeans.size() > 0) {
                for (int i = 0; i < mLonLatBeans.size(); i++) {
                    double distance = DistanceUtils.decimalFour(DistanceUtils.getDistance(offsetBean.getLon(), offsetBean.getLat(), mLonLatBeans.get(i).getLon(), mLonLatBeans.get(i).getLat()));
                    //MyLogger.i("距离" + distance);
                    if (distance > mHorizontal) {
                        mLonLatBeans.clear();
                        return null;
                    }
                }
                mLonLatBeans.add(offsetBean);

            } else {
                mLonLatBeans.add(offsetBean);
            }

        } else {
            mLonLatBeans.clear();
        }

        return offsetBean;
    }

    //测量直线
    private void line1(){

            if ((line2Count == 1) || (line3Count == 1)) {
                MyToast.show("不能更改为直线测量");
            } else {
                switch (mStartEndFlag){
                    case 0: //起点
                            if (mMeasured  !=1) {
                                mLonLatBeans.clear(); //每次测量清空
                                showDialog();
                                final RxTime rxTime = new RxTime();
                                rxTime.interval(1000, new RxTime.RxAction() {
                                    @Override
                                    public void action(long number) {
                                           getValidLatLon();
                                        if (number==300){ //超市
                                            dismissDialog();
                                            rxTime.cancel();
                                            MyToast.show("获取数据超时 请检查设备");
                                        }
                                        if (mLonLatBeans.size()==mNumber) {
                                            LonLatBean lonLatBean = average();//返回最小精准纬度                                    mLatStart = offset.getLat();
                                            mLonStart = lonLatBean.getLon();       //获取经度
                                            mLatStart = lonLatBean.getLat();       //获取经纬
                                            Log.i(Tag, "直线开始点 :" + line1Count + " 经纬度" + mLonStart + "--" + mLatStart);
                                            mSegmentBean.getStatr().setLonAndlat(mLonStart + "," + mLatStart);//保存经纬度到数据类中
                                            if ((mMeasured == 3) || (mMeasured == 4)) { //重新测量情况下 每次都计算两点距离
                                                mDistance = DistanceUtils.decimalTwo(DistanceUtils.getDistance(DistanceUtils.getLon(mSegmentBean.getEnd().getLonAndlat()), DistanceUtils.getLat(mSegmentBean.getEnd().getLonAndlat()), mLonStart, mLatStart));
                                                mTvMeasureDistance.setText("测量结果：" + mDistance);
                                                mSegmentBean.setDistance(mDistance);
                                                Log.i(Tag,"开始结果" + mDistance);
                                            }
                                            if (line1Count == 1) {// 根据经纬度算出 距离  /1 如果已经测量过一个点  代表结束 算出距离
                                                if ((mLonEnd != null) &&(mLatEnd !=null)) {
                                                    mDistance = DistanceUtils.decimalTwo(DistanceUtils.getDistance(mLonStart, mLatStart, mLonEnd, mLatEnd));
                                                    mTvMeasureDistance.setText("测量结果：" + mDistance);
                                                    mSegmentBean.setDistance(mDistance);//保存数据
                                                }
                                            }

                                            mRbStatr.setTextColor(ContextCompat.getColor(MeasureDetailActivity.this, R.color.colorBlue));
                                            line1Count = 1;
                                            dismissDialog();
                                            rxTime.cancel();
                                            MyToast.show("直线 开始点测量成功");
                                            saveData();

                                        }
                                    }
                                });
                            }else {
                                MyToast.show("请直接测量结束点");
                            }

                        break;
                    case 1: //终点
                        if (mMeasured != 2) {
                            mLonLatBeans.clear();
                            showDialog();
                            final RxTime rxTime1 = new RxTime();
                            rxTime1.interval(1000, new RxTime.RxAction() {
                                @Override
                                public void action(long number) {
                                    getValidLatLon();
                                    if (number==300){
                                        dismissDialog();
                                        rxTime1.cancel();
                                        MyToast.show("获取数据超时 请检查设备");
                                    }
                                    if (mLonLatBeans.size() == mNumber) {
                                        LonLatBean offset = average();
                                        mLatEnd = offset.getLat();
                                        mLonEnd = offset.getLon();
                                        mSegmentBean.getEnd().setLonAndlat(mLonEnd + "," + mLatEnd);
                                        Log.i(Tag, "直线结束点 :" + line1Count + " 经纬度" + mLonEnd + "--" + mLatEnd);
                                        if ((mMeasured == 3) || (mMeasured == 4)) {//重新测量情况下 每次都计算两点距离
                                            mDistance = DistanceUtils.decimalTwo(DistanceUtils.getDistance(DistanceUtils.getLon(mSegmentBean.getStatr().getLonAndlat()), DistanceUtils.getLat(mSegmentBean.getStatr().getLonAndlat()), mLonEnd, mLatEnd));
                                            mTvMeasureDistance.setText("测量结果：" + mDistance);
                                            mSegmentBean.setDistance(mDistance);
                                        }
                                        if (line1Count == 1) {//1 如果已经测量过一个点  代表结束 算出距离
                                            if ((mLonStart != null) &&(mLatStart !=null)) {
                                                mDistance = DistanceUtils.decimalTwo(DistanceUtils.getDistance(mLonStart, mLatStart, mLonEnd, mLatEnd));
                                                mTvMeasureDistance.setText("测量结果：" + mDistance);
                                                mSegmentBean.setDistance(mDistance);
                                            }
                                        }
                                        mRbEnd.setTextColor(ContextCompat.getColor(MeasureDetailActivity.this, R.color.colorBlue));
                                        line1Count = 1;
                                        dismissDialog();
                                        rxTime1.cancel();
                                        MyToast.show("直线 结束点测量成功");
                                        saveData();

                                    }
                                }
                            });
                        }else {
                            MyToast.show("请直接测量开始点");
                        }
                        break;

                }

            }

    }

     private void lineFinish(){
        if (line2Count == 1){//是否点曲线测量
            line2Count = 2;  //2 表示测量完成
            mProgressBar.setVisibility(View.INVISIBLE);//隐藏
            mTvShowStatus.setVisibility(View.INVISIBLE);
            mTvStop.setVisibility(View.INVISIBLE);
            mIvStop.setVisibility(View.INVISIBLE);
            if (mRxTime2 != null) {
                mRxTime2.cancel();
            }
            if (mStartEndFlag == 0){
                if (mMeasured !=1){
                mSegmentBean.getStatr().setLonAndlat(mLonEnd+","+mLatEnd);
                }
                mRbStatr.setTextColor(ContextCompat.getColor(MeasureDetailActivity.this,R.color.colorBlue));

            }else {
                mRbEnd.setTextColor(ContextCompat.getColor(MeasureDetailActivity.this,R.color.colorBlue));
                if (mMeasured != 2) {
                    mSegmentBean.getEnd().setLonAndlat(mLonEnd + "," + mLatEnd);
                }
            }

            double d = DistanceUtils.decimalTwo(fitting());//曲线拟合
            mSegmentBean.setMultipoint(mMultipoint); //保存连续点位 到数据类
            mSegmentBean.setDistance(d);     //保存结果到数据类
            mTvMeasureDistance.setText("测量结果：" + d);
            Log.i(Tag, "曲线拟合 :距离"+d+"点总数"+ mPointList.size());
            saveData();

        }
    }

    //曲线测量计算
    private void line2Measure(){
        if (line2Count == 0) {
            MyToast.show("曲线 开始测量");
            isStop = true;
            mIvStop.setVisibility(View.VISIBLE);//显示停止
            mTvStop.setText("停止");
            mTvStop.setVisibility(View.VISIBLE);//显示停止 继续 文本
            mProgressBar.setVisibility(View.VISIBLE);//显示定位效果图
            mTvShowStatus.setVisibility(View.VISIBLE);//显示定位中文本
            mTvShowStatus.setText("曲线测量中...");
            mRxTime2 = new RxTime();
            mRxTime2.interval(1000, new RxTime.RxAction() {
                @Override
                public void action(long number) {
                    if (isStop) {
                        if ((line3Count != 1)) {//判断上次是否是折线测量
                            if (number == 0) {//判断mMeasured 不等于 1 2 既没有测过的点传过来
                                if ((mMeasured != 1) && (mMeasured != 2)) { //开始点 结束点
                                    mLatStart = LocationBean.getInstance().getLat();
                                    mLonStart = LocationBean.getInstance().getLon();
                                    mPointList.add(new PointBean(DistanceUtils.decimalSeven(mLatStart), DistanceUtils.decimalSeven(mLonStart), 0.0));//保存第一个点
                                    Log.i(Tag, "曲线第一个点 :" + line1Count + " 经纬度" + mLonStart + "--" + mLatStart);
                                    if (mStartEndFlag == 0) {
                                        mRbStatr.setTextColor(ContextCompat.getColor(MeasureDetailActivity.this, R.color.colorBlue));
                                        mSegmentBean.getStatr().setLonAndlat(mLonStart + "," + mLatStart);
                                    } else {
                                        mRbEnd.setTextColor(ContextCompat.getColor(MeasureDetailActivity.this, R.color.colorBlue));
                                        mSegmentBean.getEnd().setLonAndlat(mLonStart + "," + mLatStart);
                                    }
                                }
                                if (mMeasured == 2) {//结束点 是传过来的值
                                    mPointList.add(new PointBean(DistanceUtils.decimalSeven(mLatEnd), DistanceUtils.decimalSeven(mLonEnd), LocationBean.getInstance().getHight()));
                                    mLatStart = mLatEnd;
                                    mLonStart = mLonEnd;
                                    if (mStartEndFlag == 0) {
                                        mRbStatr.setTextColor(ContextCompat.getColor(MeasureDetailActivity.this, R.color.colorBlue));
                                        mSegmentBean.getStatr().setLonAndlat(mLonStart + "," + mLatStart);
                                    } else {
                                        //mRbEnd.setTextColor(ContextCompat.getColor(MeasureDetailActivity.this, R.color.colorBlue));
                                      //  mSegmentBean.getEnd().setLonAndlat(mLonStart + "," + mLatStart);
                                    }
                                }
                                if (mMeasured == 1){//开始点 是传过来的值
                                    mPointList.add(new PointBean(mLatStart, mLonStart, LocationBean.getInstance().getHight()));
                                    if (mStartEndFlag == 0) {
                                       // mRbStatr.setTextColor(ContextCompat.getColor(MeasureDetailActivity.this, R.color.colorBlue));
                                        //mSegmentBean.getStatr().setLonAndlat(mLonStart + "," + mLatStart);
                                    } else {
                                        mRbEnd.setTextColor(ContextCompat.getColor(MeasureDetailActivity.this, R.color.colorBlue));
                                        mSegmentBean.getEnd().setLonAndlat(mLonStart + "," + mLatStart);
                                    }


                                }
                            }

                        }else {//折线测量改曲线
                            mLonStart = mLonLatBean.getLon(); //获取折线最后的纬度
                            mLatStart = mLonLatBean.getLat();
                            line3Count = 0;//清空折线测量状态
                            mTvCount.setVisibility(View.INVISIBLE);
                            mPointList.add(new PointBean(DistanceUtils.decimalSeven(mLonLatBean.getLat()), DistanceUtils.decimalSeven(mLonLatBean.getLon()), 0.0));
                        }
                        mLatEnd = LocationBean.getInstance().getLat();
                        mLonEnd = LocationBean.getInstance().getLon();
                        if (Double.valueOf(SharePreferenceUtils.getString(MeasureDetailActivity.this,Constant.HORIZONTAL , "0.0"))>LocationBean.getInstance().getHorizontal()) {
                            if (DistanceUtils.decimalTwo(DistanceUtils.getDistance(mLonStart, mLatStart, mLonEnd, mLatEnd)) >= 0.1) {
                                mPointList.add(new PointBean(DistanceUtils.decimalSeven(mLatEnd), DistanceUtils.decimalSeven(mLonEnd), LocationBean.getInstance().getHight()));//将有效点添加
                                mDistance = DistanceUtils.decimalTwo(mDistance + DistanceUtils.getDistance(mLonStart, mLatStart, mLonEnd, mLatEnd));
                                mMultipoint += "{" + mLonEnd + "," + mLatEnd + "}";//保存连续点 经纬度
                                mTvMeasureDistance.setText("测量结果：" + DistanceUtils.decimalTwo(mDistance));
                                mLatStart = mLatEnd;//将当前点赋值给下次开始点
                                mLonStart = mLonEnd;
                                Log.i(Tag, "连续点" + mMultipoint);
                                Log.i(Tag, "曲线每次结果" + mDistance + "----" + line1Count + "经纬度开始" + mLonStart + "--" + mLatStart + "结束" + mLonEnd + "--" + mLatEnd);
                            }
                        }

                    }
                }
            });
            line2Count=1;
        }

    }


    //曲线
    private void line2(){
        if ((line2Count == 2) ||(line3Count ==3)) {
            MyToast.show("测量已完成 无需再测量");
        } else {
            if ((line1Count == 1) ||(line1Count == 2)) {
                MyToast.show("直线测量不能更改");
            } else {
                line2Measure();

            }
        }

    }
    //折线测量
    private void line3Measure(){
        if (line3Count ==0){
            mLonLatBeans.clear();
            showDialog();
            mCount = 1;
            final RxTime rxTime3 = new RxTime();
            rxTime3.interval(1000, new RxTime.RxAction() {
                @Override
                public void action(long number) {
                    getValidLatLon();
                    if (number==300){
                        dismissDialog();
                        rxTime3.cancel();
                        MyToast.show("获取数据超时 请检查设备");
                    }
                    if (mLonLatBeans.size() == mNumber) {
                        LonLatBean offset = average();
                        mLonLatBean = offset;
                        mMultipoint += "{"+offset.getLon()+","+offset.getLat()+"}";
                        if (mStartEndFlag == 0){
                            mRbStatr.setTextColor(ContextCompat.getColor(MeasureDetailActivity.this,R.color.colorBlue));
                            mSegmentBean.getStatr().setLonAndlat(offset.getLon()+","+offset.getLat());
                        }else {
                            mRbEnd.setTextColor(ContextCompat.getColor(MeasureDetailActivity.this,R.color.colorBlue));
                            mSegmentBean.getEnd().setLonAndlat(offset.getLon()+","+offset.getLat());
                        }
                        mTvCount.setVisibility(View.VISIBLE);
                        mTvCount.setText("下次点：p1");
                        line3Count=1;
                        dismissDialog();
                        rxTime3.cancel();
                        MyToast.show("折线测量完成该点位");
                        FileUtils.log("折线第一个点：" + offset.getLon()+","+offset.getLat());
                        saveData();
                    }

                }
            });

        }else {
            if (line3Count == 1) {
                mLonLatBeans.clear();
                showDialog();
                mCount++;
                final RxTime rxTime4 = new RxTime();
                rxTime4.interval(1000, new RxTime.RxAction() {
                    @Override
                    public void action(long number) {
                        getValidLatLon();
                        if (number==300){
                            dismissDialog();
                            rxTime4.cancel();
                            MyToast.show("获取数据超时 请检查设备");
                        }
                        if (mLonLatBeans.size() == mNumber) {
                            LonLatBean offset = average();
                            mMultipoint += "{"+offset.getLon()+","+offset.getLat()+"}";
                            if (line2Count == 1) {
                                mDistance += DistanceUtils.decimalTwo(DistanceUtils.getDistance(mLonEnd, mLatEnd, offset.getLon(), offset.getLat()));
                                line2Count = 0;
                            } else {
                                mDistance += DistanceUtils.decimalTwo(DistanceUtils.getDistance(mLonLatBean.getLon(), mLonLatBean.getLat(), offset.getLon(), offset.getLat()));
                            }
                            MyLogger.i(mLonLatBean.getLon()+","+ mLonLatBean.getLat());
                            MyLogger.i(offset.getLon()+","+offset.getLat());
                            MyLogger.i(mDistance+"结果");
                            mDistance=DistanceUtils.decimalTwo(mDistance);
                            mTvMeasureDistance.setText("测量结果：" + mDistance);
                            mLonLatBean = offset;
                            dismissDialog();
                            mTvCount.setText("下次点：p" + mCount);
                            rxTime4.cancel();
                            MyToast.show("折线测量完成 中间点");
                            FileUtils.log("折线中间点：" + offset.getLon()+","+offset.getLat());
                            saveData();
                        }
                    }
                });

            }
        }
        if (line3Count ==2){
            mLonLatBeans.clear();
            showDialog();
            final RxTime rxTime4 = new RxTime();
            rxTime4.interval(1000, new RxTime.RxAction() {
                @Override
                public void action(long number) {
                    getValidLatLon();
                    if (number==300){
                        dismissDialog();
                        rxTime4.cancel();
                        MyToast.show("获取数据超时 请检查设备");
                    }
                    if (mLonLatBeans.size() == mNumber) {
                        LonLatBean offset = average();
                        mMultipoint += "{"+offset.getLon()+","+offset.getLat()+"}";
                        mDistance += DistanceUtils.decimalTwo(DistanceUtils.getDistance(mLonLatBean.getLon(), mLonLatBean.getLat(), offset.getLon(), offset.getLat()));
                        mDistance =DistanceUtils.decimalTwo(mDistance);
                        mTvMeasureDistance.setText("测量结果：" + mDistance);
                        if ((mMeasured !=1)||(mMeasured !=2)){
                                if (mStartEndFlag == 0){
                                    mLatStart = offset.getLat();
                                    mLonStart = offset.getLon();
                                    mRbStatr.setTextColor(ContextCompat.getColor(MeasureDetailActivity.this,R.color.colorBlue));
                                    mSegmentBean.getStatr().setLonAndlat(offset.getLon()+","+offset.getLat());
                                }else {
                                    mLatEnd = offset.getLat();
                                    mLonEnd = offset.getLon();
                                    mRbEnd.setTextColor(ContextCompat.getColor(MeasureDetailActivity.this,R.color.colorBlue));
                                    mSegmentBean.getEnd().setLonAndlat(offset.getLon()+","+offset.getLat());
                                }
                        }else {
                            if (mMeasured ==1){
                                mRbEnd.setTextColor(ContextCompat.getColor(MeasureDetailActivity.this,R.color.colorBlue));
                                mSegmentBean.getEnd().setLonAndlat(offset.getLon()+","+offset.getLat());
                                mLatStart = offset.getLat();
                                mLonStart = offset.getLon();
                            }else {
                                mRbStatr.setTextColor(ContextCompat.getColor(MeasureDetailActivity.this,R.color.colorBlue));
                                mSegmentBean.getStatr().setLonAndlat(offset.getLon()+","+offset.getLat());
                                mLatEnd = offset.getLat();
                                mLonEnd = offset.getLon();
                            }
                        }
                        mSegmentBean.setMultipoint(mMultipoint);
                        mSegmentBean.setDistance(mDistance);

                        dismissDialog();
                        mTvCount.setVisibility(View.INVISIBLE);
                        rxTime4.cancel();
                        MyToast.show("折线测量完成");
                        line3Count =3;
                        FileUtils.log("折线最后点：" + offset.getLon()+","+offset.getLat());
                        saveData();

                    }
                }
            });
        }

    }
    //折线
    private void line3(){
        if ((line3Count == 3)||(line2Count == 2)) {
            MyToast.show("测量已完成 无需再测量");
        } else {
            if ((line1Count == 1) ||(line1Count == 2)) {
                MyToast.show("直线测量不能更改");
            } else {
                line3Measure();


            }
        }
    }

    //保存测量过过程的数据
    private void saveData(){
            mSegmentBean.setCount(mCount);
            mSegmentBean.setDistance(mDistance);
            mSegmentBean.setLatEnd(mLatEnd);
            mSegmentBean.setLatEnd(mLatEnd);
            mSegmentBean.setLatStart(mLatStart);
            mSegmentBean.setLatEnd(mLatEnd);
            mSegmentBean.setLineType(mLine);
            mSegmentBean.setLine1Count(line1Count);
            mSegmentBean.setLine2Count(line2Count);
            mSegmentBean.setLine3Count(line3Count);
            mSegmentBean.setMultipoint(mMultipoint);
            mSegmentBean.setStartEndFlag(mStartEndFlag);
            mSegmentBean.setLonLat(mLonLatBean);
            //mSegmentBean.setSave(true);
            Gson gson = new Gson();
            SharePreferenceUtils.putString(MeasureDetailActivity.this, crashSegment, gson.toJson(mSegmentBean));

    }
    //定位
    private void location(){
        try {

            int pos = LocationBean.getInstance().getPos();//获取定位状态
            if ((pos == 16) || (pos == 17) || (pos == 50) || (pos == 34) /*|| (pos == 0)*/) {
                if (((Double.valueOf(SharePreferenceUtils.getString(this, Constant.VERTRCAL, "2")) > LocationBean.getInstance().getVertrcal())
                        && (mHorizontal > LocationBean.getInstance().getHorizontal()))) {
                    isResult = false; //手动输入标识
                    switch (mLine) {
                        case 1:
                            line1();//直线
                            break;
                        case 2:
                            line2();//曲线
                            break;
                        case 3:
                            line3(); //折线
                            break;
                    }
                } else {
                    MyToast.show("精度不足 请更改精度设置范围");
                    startMediaPlayer();//播放警告声音
                }


            } else {
                MyToast.show("未结算 请将设备移动空旷位置");
                startMediaPlayer();
            }
        }catch (Exception e){
            MyCrashHandler.newInstance().saveCrashInfoToFile(e);

        }

    }


     //测量完成
    private void showSaveDialog(){

        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setTitle("测量完成");
        normalDialog.setCancelable(false);
        normalDialog.setMessage("是否保存");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SharePreferenceUtils.putString(MeasureDetailActivity.this, crashSegment, "");
                        if (isResult){
                            mSegmentBean.setState(5);
                        }
                        DistanceUtils.saveState(MeasureDetailActivity.this,1);
                        Intent intent = new Intent();
                        intent.putExtra("data",mSegmentBean );
                        //intent.putIntegerArrayListExtra("start", (ArrayList<Integer>) mSegmentBean.getStatr().getGroupId());
                       // intent.putIntegerArrayListExtra("end", (ArrayList<Integer>) mSegmentBean.getEnd().getGroupId());
                        setResult(2, intent);
                        finish();

                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        normalDialog.show();
    }

    @Override
    public void onBackPressed() {
        showDialogBack();//back键  弹出对话框
    }

    //显示退出对话框
    private void showDialogBack(){
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setTitle("退出");
        normalDialog.setCancelable(false);
        normalDialog.setMessage("是否退出并保存");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Gson gson = new Gson();
                        SharePreferenceUtils.putString(MeasureDetailActivity.this, crashSegment, gson.toJson(mSegmentBean));
                        finish();
                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SharePreferenceUtils.putString(MeasureDetailActivity.this, crashSegment, "");
                        dialog.dismiss();
                        finish();
                    }
                });
        normalDialog.show();

    }

    //重新测量
    private void showAgainDialog(){
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setTitle("重测");
        normalDialog.setCancelable(false);
        normalDialog.setMessage("是否重新测量");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                         againMeasure();

                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        normalDialog.show();

    }


    /**
     * 恢复对话框
     * @param json 上次保存Segment
     */
    private void showRecoverDialog(final String json){

        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setTitle("恢复");
        normalDialog.setCancelable(false);
        normalDialog.setMessage("上次未完成测量是否继续");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        recover(json);
                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        initSegment();
                        dialog.dismiss();
                    }
                });
        normalDialog.show();
    }


}
